import { constantRoutes } from "@/router";
import { getRouters } from "@/api/menu";
import Layout from "@/layout/index";
import user from "./user";

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    sidebarRouters: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    },
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = routers;
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise((resolve) => {
        // 向后端请求路由数据
        getRouters().then((res) => {
          let data = [];
          if (user.state.userLevel) {
            data = res.data
              .map((item) => {
                if (item.path == "/nonOil") {
                  return item;
                }
              })
              .filter((item2) => item2 !== undefined);
          } else {
            data = res.data
              .map((item) => {
                if (item.path == "/nonOil" || item.path == "/system") {
                  let dataList = [];
                  if (item.path == "/system") {
                    item.children.forEach((item) => {
                      if (
                        item.path == "user" ||
                        item.path == "role" ||
                        item.path == "menu" ||
                        item.path == "post" ||
                        item.path == "dept"
                      ) {
                        dataList.push(item);
                      }
                    });
                    item.children = dataList;
                  }
                  return item;
                }
              })
              .filter((item2) => item2 !== undefined);
          }

          const sdata = JSON.parse(JSON.stringify(data));
          const sidebarRoutes = filterAsyncRouter(sdata);
          const accessedRoutes = filterAsyncRouter(data);
          console.log("accessedRoutes", accessedRoutes);
          console.log("sidebarRoutes", sidebarRoutes);
          accessedRoutes.push({ path: "*", redirect: "/404", hidden: true });
          commit("SET_ROUTES", accessedRoutes);
          commit("SET_SIDEBAR_ROUTERS", sidebarRoutes);
          resolve(accessedRoutes);
        });
      });
    },
  },
};

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter((route) => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === "Layout") {
        route.component = Layout;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children);
    }
    return true;
  });
}

export const loadView = (view) => {
  if (process.env.NODE_ENV === "development") {
    return (resolve) => require([`@/views/${view}`], resolve);
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`);
  }
};

export default permission;
